package com.stars.questions.deptQuestion.config.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.stars.questions.deptQuestion.config.entity.Organizes;
import com.stars.questions.deptQuestion.config.entity.Question;
import com.stars.questions.deptQuestion.config.entity.QuestionConfigDTO;
import com.stars.questions.deptQuestion.config.entity.QuestionSub;
import com.stars.questions.deptQuestion.config.mapper.DeptMapper;
import com.stars.questions.deptQuestion.config.mapper.QuestionMapper;
import com.stars.questions.deptQuestion.config.mapper.QuestionSubMapper;
import com.stars.questions.deptQuestion.config.mapper.ReplyMapper;
import com.stars.questions.deptQuestion.config.service.QuestionConfigService;
import com.stars.questions.deptQuestion.publish.entity.Reply;
import com.stars.util.common.DevelopKit;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.*;

/**
 * @author : Rocks
 * @version : 1.0
 * @date : 2022/10/2 19:52
 * @description : 问卷配置服务实现类
 */
@Service
public class QuestionConfigServiceImpl implements QuestionConfigService {

    private final QuestionMapper questionMapper;
    private final QuestionSubMapper subMapper;
    private final DeptMapper deptMapper;
    private final ReplyMapper replyMapper;

    public QuestionConfigServiceImpl(QuestionMapper questionMapper, QuestionSubMapper subMapper, DeptMapper deptMapper,ReplyMapper replyMapper) {
        this.questionMapper = questionMapper;
        this.subMapper = subMapper;
        this.deptMapper = deptMapper;
        this.replyMapper = replyMapper;
    }

    @Override
    public JSONObject data(QuestionConfigDTO dto) {

        JSONObject result = new JSONObject();

        Page<Question> page = Page.of(dto.getCurrent(), dto.getPageSize());
        LambdaQueryWrapper<Question> queryWrapper = new LambdaQueryWrapper<>();

        if(StringUtils.hasLength(dto.getSearch())){
            queryWrapper.like(Question::getBt, dto.getSearch());
        }

        Page<Question> questionPage = questionMapper.selectPage(page, queryWrapper);

        result.put("list", questionPage.getRecords() );
        result.put("total", questionPage.getTotal());

        return result;
    }

    @Override
    public boolean check(String year) {

        LambdaQueryWrapper<Question> query = new LambdaQueryWrapper<>();

        query.eq(Question::getYear,year);

        return questionMapper.exists(query);
    }

    @Override
    @Transactional
    public JSONObject publish(String id) {

        JSONObject result = new JSONObject();
        result.put("result",false);

        LambdaQueryWrapper<Question> queryWrapper = new LambdaQueryWrapper<>();

        queryWrapper.eq(Question::getPublish, 1);
        queryWrapper.lt(Question::getStartDate, new Date());
        queryWrapper.gt(Question::getEndDate, new Date());

        Question question = questionMapper.selectOne(queryWrapper);

        if(question!=null&&id.equals(question.getId())){
            //当前问卷调查已经发布
            result.put("msg","当前问卷已发布！");
            return result;
        }

        Question temp = new Question();
        temp.setPublish(-1);

        queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.ne(Question::getId,id);

        //取消发布非本数据的问卷
        if(questionMapper.update(temp,queryWrapper) < 1){
            result.put("msg","取消发布异常！");
            return result;
        }

        temp = new Question();
        temp.setPublish(1);

        queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Question::getId,id);

        //发布本数据
        if(questionMapper.update(temp,queryWrapper) < 1){
            result.put("msg","发布异常！");
            return result;
        }

        result.put("result",true);
        return result;
    }

    @Override
    public boolean unPublish(String id) {

        Question question = new Question();
        question.setId(id);
        question.setPublish(-1);

        return questionMapper.updateById(question) > 0;
    }

    @Override
    public Question getPublishQuestion() {

        LambdaQueryWrapper<Question> queryWrapper = new LambdaQueryWrapper<>();

        queryWrapper.eq(Question::getPublish, 1);
        queryWrapper.lt(Question::getStartDate, new Date());
        queryWrapper.gt(Question::getEndDate, new Date());

        return questionMapper.selectOne(queryWrapper);
    }

    @Override
    @Transactional
    public boolean save(Question question) {
        if(!StringUtils.hasLength(question.getId())){
            //新增
            String configId = DevelopKit.generateUUID();

            question.setId(configId);
            DevelopKit.setBaseInfo(question);

            if(questionMapper.insert(question)<1){
                return false;
            }

            for (QuestionSub sub : question.getQuestions()) {

                sub.setId(DevelopKit.generateUUID());
                sub.setFid(configId);
                sub.setRowStatus(1);

                if(subMapper.insert(sub) < 1){
                    return false;
                }
            }

        }else{
            //更新
            if(questionMapper.updateById(question) < 1){
                return false;
            }

            for (QuestionSub sub : question.getQuestions()) {

                if(!StringUtils.hasLength(sub.getId())){
                    //子表执行新增操作
                    sub.setId(DevelopKit.generateUUID());
                    sub.setFid(question.getId());
                    sub.setRowStatus(1);

                    if(subMapper.insert(sub) < 1){
                        return false;
                    }

                }else{
                    //子表执行更新操作
                    if(subMapper.updateById(sub) < 1){
                        return false;
                    }
                }
            }
        }

        return true;
    }

    /**
     * 删除数据
     *
     * @param id 要删除的数据
     * @return JSONObject
     * @author : Rocks
     * @date :  2022/10/2 23:01
     */
    @Override
    public boolean delRecord(String id) {
        return questionMapper.deleteById(id) > 0;
    }

    @Override
    public Question loadQuestion(String id) {

        LambdaQueryWrapper<QuestionSub> queryWrapper = new LambdaQueryWrapper<>();

        queryWrapper.eq(QuestionSub::getFid,id);
        queryWrapper.orderByAsc(QuestionSub::getShowOrder);

        Question question = questionMapper.selectById(id);
        List<QuestionSub> subs = subMapper.selectList(queryWrapper);

        question.setQuestions(subs);

        return question;
    }

    @Override
    public List<QuestionSub> loadQuestionSub(String id,String mark) {

        LambdaQueryWrapper<QuestionSub> queryWrapper = new LambdaQueryWrapper<>();

        queryWrapper.eq(QuestionSub::getFid,id);
        queryWrapper.orderByAsc(QuestionSub::getShowOrder);

        List<QuestionSub> questionSubs = subMapper.selectList(queryWrapper);
        if(!StringUtils.hasLength(mark)){
            return questionSubs;
        }
        for(QuestionSub sub : questionSubs){
            String orgName =  sub.getOrgName();
            String question = sub.getQuestion();
            sub.setQuestion(mark.replaceAll("\\[dept]",orgName).replaceAll("\\[question]",question));
        }

        return questionSubs;
    }

    @Override
    public boolean deleteSub(String subId) {
        return subMapper.deleteById(subId) > 0;
    }

    @Override
    @Transactional
    public boolean initDept(String id) {

        LambdaQueryWrapper<QuestionSub> queryWrapper = new LambdaQueryWrapper<>();

        queryWrapper.eq(QuestionSub::getFid,id);
        queryWrapper.orderByAsc(QuestionSub::getShowOrder);

        int order = 1;

        List<QuestionSub> questionSubs = subMapper.selectList(queryWrapper);
        Set<String> sets = new HashSet<>();
        if(questionSubs!=null){
            for(QuestionSub sub : questionSubs){
                int showOrder = sub.getShowOrder();
                if(showOrder>order){
                    order = showOrder;
                }
                sets.add(sub.getOrgId());
            }
        }

        LambdaQueryWrapper<Organizes> orgQuery = new LambdaQueryWrapper<>();

        orgQuery.eq(Organizes::getStatus,1);
        orgQuery.orderByAsc(Organizes::getShowOrder);

        List<Organizes> deptArr = deptMapper.selectList(orgQuery);

        boolean flag = true;
        for(Organizes org: deptArr){

            if(!sets.contains(org.getId())){
                //子表执行新增操作
                order = order+2;
                QuestionSub sub = new QuestionSub();
                sub.setId(DevelopKit.generateUUID());
                sub.setFid(id);
                sub.setOrgId(org.getId());
                sub.setShowOrder(order);

                flag = subMapper.insert(sub) > 0;
            }
        }

        return flag;
    }

    public Set<Integer> generateRandomNum(Question question,int questionCount) {
        if(question.getNum()<1){
            return null;
        }
        Random random = new Random();

        Set<Integer> set = new HashSet<>();

        while(set.size()<question.getNum()){
            int index = random.nextInt(questionCount);
            set.add(index);
        }

        return set;
    }

    /**
     * 功能描述: 同手机号只能提交一次
     * @param:
     * @return:
     * @auther: Administrator
     * @date: 2023/12/4 10:36
     */
    @Override
    public boolean checkSubmit(Reply reply){
        LambdaQueryWrapper<Reply> replyWrapper = new LambdaQueryWrapper<>();
        replyWrapper.eq(Reply::getMobile,reply.getMobile())
                .eq(Reply::getConfigId,reply.getConfigId());
        return this.replyMapper.exists(replyWrapper);
    }
}
